package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.TreeProblem;

/**
 * 候选人思路: 中序遍历放到数组中, 判断数组单调
 * @author tzp
 * @since 2020/10/13
 */
public class LC98 implements TreeProblem {
    public static class Pair<A, B> {
        public A a;
        public B b;

        public Pair(A a, B b) {
            this.a = a;
            this.b = b;
        }
    }

    boolean isValid = true;

    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        rec(root);
        return isValid;
    }

    public Pair<Integer, Integer> rec(TreeNode root) {
        if (root == null) return null;
        Integer min = root.val, max = root.val;
        if (root.left != null) {
            Pair<Integer, Integer> leftResult = rec(root.left);
            if (!isValid) return null;
            if (leftResult.b >= root.val) {
                isValid = false;
                return null;
            }
            min = leftResult.a;
        }

        if (root.right != null) {
            Pair<Integer, Integer> rightResult = rec(root.right);
            if (!isValid) return null;
            if (rightResult.a <= root.val) {
                isValid = false;
                return null;
            }
            max = rightResult.b;
        }
        return new Pair<>(min, max);
    }

    public static void main(String[] args) {
        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        System.out.println(new LC98().isValidBST(treeNode));
    }
}
